from odoo import api, fields, models
from odoo.exceptions import UserError
import logging

QA_STATE = [('create', '创建'), ('enable', '启用'), ('publish', '发布'), ('deprecation', '下架'), ('disable', '弃用')]

_logger = logging.getLogger(__name__)


class RpQuestionAndAnswer(models.Model):
    _name = 'rp.question.and.answer'
    _description = 'Q&A 文章管理'

    # 基础
    name = fields.Char(string='名称', related='title', store=True, copy=False)
    code = fields.Char(string='编码')
    question_answer_level_id = fields.Many2one(string='级别', comodel_name='rp.question.and.answer.level', required=True, copy=False)
    keywords_ids = fields.Many2many(string='关键字', comodel_name='rp.question.answer.keyword', column1='rp_question_and_answer_id', column2='question_keyword_id',
                                    relation='rp_question_and_answer_keyword_rel', help='关键字只有一类具有')

    # 方便进行隐藏字段
    is_root = fields.Boolean(string='是否为根', related='question_answer_level_id.is_root', copy=False)
    level_name = fields.Char(string='级别名称', related='question_answer_level_id.name', copy=False)
    question_answer_type_ids = fields.Many2many(string='类型', comodel_name='rp.question.and.answer.type', column1='rp_question_and_answer_id',
                                                column2='rp_question_type_id', relation='rp_question_and_answer_rp_question_type_rel', required=True, copy=False)

    # 图片
    cover = fields.Binary(string='封面', attachment=True)
    cover_display = fields.Binary(string='封面', related='cover')
    cover_name = fields.Char(string='文件名')

    # 文章信息
    author = fields.Many2one(string='作者', comodel_name='res.users', required=True)
    title = fields.Char(string='标题', translate=True, copy=False, required=True)
    sub_title = fields.Char(string='副标题', translate=True, copy=False, required=True)
    introduction = fields.Char(string='简介')
    body = fields.Html(string='内容')

    # 时间
    publish_time = fields.Datetime(string='发布时间', copy=False)
    deprecation_time = fields.Datetime(string='下架时间', copy=False)
    disable_time = fields.Datetime(string='弃用时间', copy=False)
    enable_time = fields.Datetime(string='启用时间', copy=False)

    related_question_and_answer_ids = fields.Many2many(string='推荐Q&A', comodel_name='rp.question.and.answer', column1='rp_question_and_answer_id',
                                                       column2='rp_question_and_answer_related_id', relation='rp_question_and_answer_rp_question_and_answer_rel', copy=False)

    correlation_next_level_ids = fields.One2many(string='关联的下一级Q&A', comodel_name='rp.question.and.answer', inverse_name='rp_question_and_answer_id', copy=False)
    rp_question_and_answer_id = fields.Many2one(string='上一级Q&A', comodel_name='rp.question.and.answer', copy=False)

    state = fields.Selection(string='状态', selection=QA_STATE, default=QA_STATE[0][0])
    publish_flag = fields.Boolean(string='发布标志', default=False)

    """
    Native
    """

    @api.model_create_single
    def create(self, values):
        values['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.question.and.answer') or '/'
        context = self.env.context.copy()
        context.update({'upload': True, 'res_model': 'rp.question.and.answer', 'file_name': values.get('cover_name')})
        return super(RpQuestionAndAnswer, self.with_context(context)).create(values)

    def write(self, vals):
        self.env['ir.attachment'].clear_caches()
        ir_attachment_id = self.env['ir.attachment'].search([('res_field', '=', 'cover'), ('res_id', '=', self.id)])
        if ir_attachment_id:
            ir_attachment_id.unlink()
        context = self.env.context.copy()
        context.update({'upload': True, 'res_model': 'rp.question.and.answer', 'file_name': vals.get('cover_name')})
        # 触发保存至附件的逻辑
        return super(RpQuestionAndAnswer, self.with_context(context)).write(vals)

    def name_get(self):
        result = []
        for record in self:
            result.append((record.id, f'{record.title}【{record.code}】'))
        return result

    def unlink(self):
        """
        删除限制
        """
        next_level_question_and_answer_state = self.correlation_next_level_ids.filtered(lambda r: r.state == 'publish' and r.publish_flag is True)
        if len(next_level_question_and_answer_state) > 0:
            raise UserError('此问答关联的下一级问答存在已发布的问答，无法删除！')
        return super(RpQuestionAndAnswer, self).unlink()

    """
    Onchange
    """

    @api.onchange('state')
    def onchange_state(self):
        if self.state == 'enable':
            self.update({'enable_time': fields.Datetime.now()})

    @api.onchange('question_answer_level_id')
    def onchange_question_and_answer_level(self):
        # 清除上一级Q&A问答和下一级的Q&A问答
        self.update({
            'rp_question_and_answer_id': False,
            'correlation_next_level_ids': [(5, 0, 0)]
        })
        level_name = self.question_answer_level_id.name
        if level_name == 'Level Two':
            available_level = self.env['rp.question.and.answer.level'].search([('name', '=', 'Level One')])
            return {'domain': {'rp_question_and_answer_id': [('question_answer_level_id', '=', available_level.id)]}}
        elif level_name == 'Level Three':
            available_level = self.env['rp.question.and.answer.level'].search([('name', '=', 'Level Two')])
            return {'domain': {'rp_question_and_answer_id': [('question_answer_level_id', '=', available_level.id)]}}
        else:
            # 给出一个不存在的ID值
            return {'domain': {'rp_question_and_answer_id': [('question_answer_level_id', '=', 9999999)]}}

    """
    Button Function
    """

    def turn_publish(self):
        """
        发布【弃用先启用再发布】【下架状态的仍是启用，只不过下架了】
        """
        origin_state = self.state
        if origin_state in ['create', 'disable']:
            raise UserError(f'目前状态为【{origin_state}】,需要先启用后再发布！')
        if origin_state == 'publish':
            raise UserError('状态已经为已发布！')
        self.write({'state': 'publish', 'publish_time': fields.Datetime.now(), 'publish_flag': True})

    def turn_deprecation(self):
        """
        下架【已发布才可以下架】
        """
        origin_state = self.state
        if origin_state != 'publish':
            raise UserError('只有已发布才可以下架！')
        if origin_state == 'deprecation':
            raise UserError('状态已经为下架状态！')
        self.write({'state': 'deprecation', 'deprecation_time': fields.Datetime.now()})

    def turn_disable(self):
        """
        弃用【只有创建，弃用状态不可弃用】
        """
        origin_state = self.state
        if origin_state == 'disable':
            raise UserError('状态已经为弃用状态！')
        self.write({'state': 'disable', 'disable_time': fields.Datetime.now()})

    def turn_enable(self):
        """
        启用【弃用状态才可以启用】
        """
        origin_state = self.state
        if origin_state != 'disable':
            raise UserError(f'状态【({origin_state})】不可弃用！')
        if origin_state == 'enable':
            raise UserError('状态已经为启用状态！')
        self.write({'state': 'enable', 'enable_time': fields.Datetime.now()})


class RpQuestionAndAnswerType(models.Model):
    _name = 'rp.question.and.answer.type'
    _description = 'Q&A 问答类型'

    name = fields.Char(string='名称', copy=False, required=True)


class RpQuestionAnswerLevel(models.Model):
    _name = 'rp.question.and.answer.level'
    _description = 'Q&A问答等级'

    name = fields.Char(string='问答级别', copy=False, required=True)
    is_root = fields.Boolean(string='是否为根', default=False)
    parent_level_id = fields.Many2one(string='上一级', comodel_name='rp.question.and.answer.level', copy=False)


class RpQuestionAnswerKeyword(models.Model):
    _name = 'rp.question.answer.keyword'
    _description = 'Q&A关键字'

    name = fields.Char(string='名称', copy=False, required=True)
